<template>
	<div class="planStatus-container" v-loading="state.exportLoading">
		<el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
			<el-form :model="state.tableQueryParams" ref="queryForm" labelWidth="90">
				<el-row>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
						<el-form-item label="关键字">
							<el-input v-model="state.tableQueryParams.keyword" clearable placeholder="请输入船号或分段关键字" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="船号">
							<el-input v-model="state.tableQueryParams.ch" clearable placeholder="请输入船号" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="分段">
							<el-input v-model="state.tableQueryParams.fd" clearable placeholder="请输入分段" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="工作月份">
							<el-date-picker v-model="state.tableQueryParams.workTime" type="month" value-format="YYYY-MM" placeholder="请选择工作月份" clearable style="width: 100%" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="分类">
							<el-select clearable filterable v-model="state.tableQueryParams.className" placeholder="请选择分类" style="width: 100%">
								<el-option v-for="(item, index) in state.dropdownData.className ?? []" :key="index" :value="item.value" :label="item.label" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="区域">
							<el-select clearable filterable v-model="state.tableQueryParams.workAreaId" placeholder="请选择区域" style="width: 100%">
								<el-option v-for="(item, index) in state.dropdownData.workAreaId ?? []" :key="index" :value="item.value" :label="item.label" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="状态">
							<el-select v-model="state.tableQueryParams.status" placeholder="请选择状态" clearable style="width: 100%">
								<el-option label="进行中" :value="0" />
								<el-option label="已完成" :value="1" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.incompleteStatistics">
						<el-form-item>
							<el-button-group style="display: flex; align-items: center">
								<el-button type="primary" icon="ele-Search" @click="handleQuery" v-auth="'planStatus:page'" v-reclick="1000"> 查询 </el-button>
								<el-button icon="ele-Refresh" @click="resetQuery"> 重置 </el-button>
								<el-button icon="ele-ZoomIn" @click="() => (state.showAdvanceQueryUI = true)" v-if="!state.showAdvanceQueryUI" style="margin-left: 5px"> 高级查询 </el-button>
								<el-button icon="ele-ZoomOut" @click="() => (state.showAdvanceQueryUI = false)" v-if="state.showAdvanceQueryUI" style="margin-left: 5px"> 隐藏 </el-button>
								<el-button type="danger" style="margin-left: 5px" icon="ele-Delete" @click="batchDelPlanStatus" :disabled="state.selectData.length == 0" v-auth="'planStatus:batchDelete'">
									删除
								</el-button>
								<el-button type="primary" style="margin-left: 5px" icon="ele-Plus" @click="editDialogRef.openDialog(null, '新增计划状态')" v-auth="'planStatus:add'"> 新增 </el-button>
								<el-button
									type="info"
									style="margin-left: 5px"
									icon="ele-DataAnalysis"
									@click="openIncompleteItemsDialog"
									v-auth="'planStatus:page'"
									:disabled="state.incompleteStatistics.problematicSegments === 0"
								>
									未完成项管理 ({{ state.incompleteStatistics.problematicSegments }})
								</el-button>
								<el-dropdown :show-timeout="70" :hide-timeout="50" @command="exportPlanStatusCommand">
									<el-button type="primary" style="margin-left: 5px" icon="ele-FolderOpened" v-reclick="20000" v-auth="'planStatus:export'"> 导出 </el-button>
									<template #dropdown>
										<el-dropdown-menu>
											<el-dropdown-item command="select" :disabled="state.selectData.length == 0">导出选中</el-dropdown-item>
											<el-dropdown-item command="current">导出本页</el-dropdown-item>
											<el-dropdown-item command="all">导出全部</el-dropdown-item>
										</el-dropdown-menu>
									</template>
								</el-dropdown>
								<el-button type="warning" style="margin-left: 5px" icon="ele-MostlyCloudy" @click="importDataRef.openDialog()" v-auth="'planStatus:import'"> 导入 </el-button>
							</el-button-group>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</el-card>

		<!-- 未完成项统计卡片 -->
		<!-- <el-card shadow="hover" style="margin-top: 5px" v-if="state.incompleteStatistics"> -->
		<!-- <template #header>
				<div style="display: flex; justify-content: space-between; align-items: center">
					<span style="font-weight: bold; color: #409eff">
						<el-icon><Warning /></el-icon> 数据质量监控
					</span>
					<el-button type="text" size="small" @click="refreshIncompleteStatistics">
						<el-icon><Refresh /></el-icon> 刷新
					</el-button>
				</div>
			</template>
			<el-row :gutter="20">
				<el-col :span="4">
					<div class="stat-card">
						<div class="stat-number">{{ state.incompleteStatistics.totalSegments }}</div>
						<div class="stat-label">总分段数</div>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="stat-card">
						<div class="stat-number">{{ state.incompleteStatistics.finishedSegments }}</div>
						<div class="stat-label">已完成分段</div>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="stat-card danger">
						<div class="stat-label">问题分段</div>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="stat-card warning">
						<div class="stat-number">{{ state.incompleteStatistics.totalIncompleteItems }}</div>
						<div class="stat-label">待补充项</div>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="stat-card">
						<div class="stat-number">{{ state.incompleteStatistics.problematicRate }}%</div>
						<div class="stat-label">问题比例</div>
					</div>
				</el-col>
				<el-col :span="4">
					<div style="display: flex; align-items: center; height: 100%">
						<el-button type="danger" size="default" @click="openIncompleteItemsDialog" :disabled="state.incompleteStatistics.problematicSegments === 0">
							<el-icon><EditPen /></el-icon> 立即处理 ({{ state.incompleteStatistics.problematicSegments }})
						</el-button>
					</div>
				</el-col>
			</el-row> -->

		<!-- 问题分段预览 -->
		<!-- <div v-if="state.incompleteStatistics.problematicSegmentsList.length > 0" style="margin-top: 15px">
				<el-divider content-position="left">
					<span style="color: #f56c6c; font-weight: bold">
						<el-icon><WarningFilled /></el-icon> 问题分段预览（前10项）
					</span>
				</el-divider>
				<el-table :data="state.incompleteStatistics.problematicSegmentsList" size="small" stripe style="width: 100%" max-height="200">
					<el-table-column prop="ch" label="船号" width="100" align="center" />
					<el-table-column prop="fd" label="分段" width="100" align="center" />
					<el-table-column prop="finishDate" label="分段报验完工" width="150" align="center">
						<template #default="scope">
					<el-tag type="success" size="small">{{ formatDate(scope.row.finishDate ?? null) }}</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="incompleteCount" label="缺失项数" width="100" align="center">
						<template #default="scope">
							<el-tag type="danger" size="small">{{ scope.row.incompleteCount }}</el-tag>
						</template>
					</el-table-column>
					<el-table-column label="具体缺失" min-width="300">
						<template #default="scope">
							<div style="display: flex; flex-wrap: wrap; gap: 4px">
								<el-tag v-for="(item, index) in scope.row.incompleteItems" :key="index" size="small" :type="item.missingStart && item.missingEnd ? 'danger' : 'warning'">
									{{ item.className }}
									<span v-if="item.missingStart">缺开工</span>
									<span v-if="item.missingStart && item.missingEnd">+</span>
									<span v-if="item.missingEnd">缺完工</span>
								</el-tag>
							</div>
						</template>
					</el-table-column>
				</el-table>
			</div> -->
		<!-- </el-card> -->

		<el-card class="full-table" shadow="hover" style="margin-top: 5px">
			<!-- 表格模式 -->
			<el-table
				v-if="state.displayMode === 'table'"
				:data="state.tableData"
				@selection-change="
					(val: any[]) => {
						state.selectData = val;
					}
				"
				style="width: 100%"
				v-loading="state.tableLoading"
				tooltip-effect="light"
				row-key="id"
				@sort-change="sortChange"
				border
			>
				<el-table-column type="selection" width="40" align="center" fixed="left" v-if="auth('planStatus:batchDelete') || auth('planStatus:export')" />
				<el-table-column type="index" label="序号" width="55" fixed="left" align="center" />
				<el-table-column prop="ch" label="船号" width="100" align="center" fixed="left" show-overflow-tooltip />
				<el-table-column prop="fd" label="分段" width="100" align="center" fixed="left" show-overflow-tooltip />

					<!-- 动态生成分类列 -->
					<el-table-column v-for="category in state.categoryColumns" :key="category.className" :label="category.classNameFkDisplayName" width="250" align="center" show-overflow-tooltip>
						<el-table-column :prop="'categories.' + category.className + '.actualStart'" label="开工" width="125" align="center" show-overflow-tooltip>
						<template #default="scope">
							<div style="display: flex; align-items: center; gap: 8px; justify-content: center; width: 100%">
								<!-- 开工延期指示器 -->
								<el-popover v-if="Number(getCategory(scope.row, category.className)?.startDelayDays) >= 7" placement="top" :width="250" trigger="click">
									<template #reference>
										<div
											style="
												background: #ff4d4f;
												color: white;
												border-radius: 50%;
												width: 20px;
												height: 20px;
												font-size: 11px;
												font-weight: bold;
												display: flex;
												align-items: center;
												justify-content: center;
												border: 1px solid white;
												box-shadow: 0 1px 4px rgba(255, 77, 79, 0.4);
												cursor: pointer;
												flex-shrink: 0;
											"
										>
											{{ getCategory(scope.row, category.className)?.startDelayDays }}
										</div>
									</template>
									<div>
										<div style="margin-bottom: 10px; font-weight: bold">开工延期信息</div>
										<div style="font-size: 12px; color: #606266">延期天数: {{ getCategory(scope.row, category.className)?.startDelayDays }} 天</div>
									</div>
								</el-popover>
									<el-tooltip placement="top">
										<template #content>
											计划开工：{{ formatDate(getCategory(scope.row, category.className)?.planStart ?? null) }}
										</template>
										<span style="flex-shrink: 0">{{ formatDate(getCategory(scope.row, category.className)?.actualStart ?? null) }}</span>
									</el-tooltip>
							</div>
						</template>
					</el-table-column>

						<el-table-column :prop="'categories.' + category.className + '.actualEnd'" label="完工" width="125" align="center" show-overflow-tooltip>
						<template #default="scope">
							<div style="display: flex; align-items: center; gap: 8px; justify-content: center; width: 100%">
								<!-- 延期指示器 -->
								<el-popover v-if="Number(getCategory(scope.row, category.className)?.endDelayDays) >= 7" placement="top" :width="250" trigger="click">
									<template #reference>
										<div
											style="
												background: #ff4d4f;
												color: white;
												border-radius: 50%;
												width: 20px;
												height: 20px;
												font-size: 11px;
												font-weight: bold;
												display: flex;
												align-items: center;
												justify-content: center;
												border: 1px solid white;
												box-shadow: 0 1px 4px rgba(255, 77, 79, 0.4);
												cursor: pointer;
												flex-shrink: 0;
											"
										>
											{{ getCategory(scope.row, category.className)?.endDelayDays }}
										</div>
									</template>
									<div>
										<div style="margin-bottom: 10px; font-weight: bold">完工延期信息</div>
										<div style="font-size: 12px; color: #606266">延期天数: {{ getCategory(scope.row, category.className)?.endDelayDays }} 天</div>
									</div>
								</el-popover>
									<el-tooltip placement="top">
										<template #content>
											计划完工：{{ formatDate(getCategory(scope.row, category.className)?.planEnd ?? null) }}
										</template>
										<span class="date-value" style="flex-shrink: 0; flex: none; text-align: center">{{ formatDate(getCategory(scope.row, category.className)?.actualEnd ?? null) }}</span>
									</el-tooltip>
							</div>
						</template>
					</el-table-column>
				</el-table-column>

				<!-- 最终状态列固定在右侧 -->
				<el-table-column label="最终状态" width="100" align="center" fixed="right" show-overflow-tooltip>
					<template #default="scope">
						<el-tag :type="getStatusType(scope.row.isAllFinished)" size="small">
							{{ scope.row.isAllFinished ? '已完成' : '进行中' }}
						</el-tag>
					</template>
				</el-table-column>

				<el-table-column label="操作" width="140" align="center" fixed="right" show-overflow-tooltip v-if="auth('planStatus:update') || auth('planStatus:delete')">
					<template #default="scope">
						<el-button icon="ele-Edit" size="small" text type="primary" @click="editDialogRef.openDialog(scope.row, '编辑计划状态')" v-auth="'planStatus:update'"> 编辑 </el-button>
						<el-button icon="ele-Delete" size="small" text type="primary" @click="delPlanStatus(scope.row)" v-auth="'planStatus:delete'"> 删除 </el-button>
					</template>
				</el-table-column>
			</el-table>

			<!-- 纵向模式 -->
			<el-table
				v-if="state.displayMode === 'compact'"
				:data="state.tableData"
				@selection-change="
					(val: any[]) => {
						state.selectData = val;
					}
				"
				style="width: 100%"
				v-loading="state.tableLoading"
				tooltip-effect="light"
				row-key="id"
				@sort-change="sortChange"
				border
			>
				<el-table-column type="selection" width="40" align="center" fixed="left" v-if="auth('planStatus:batchDelete') || auth('planStatus:export')" />
				<el-table-column type="index" label="序号" width="55" align="center" fixed="left" />
				<el-table-column prop="ch" label="船号" width="100" align="center" fixed="left" show-overflow-tooltip />
				<el-table-column prop="fd" label="分段" width="100" align="center" fixed="left" show-overflow-tooltip />

				<!-- 纵向模式的分类列 -->
					<el-table-column v-for="category in state.categoryColumns" :key="category.className" :label="category.classNameFkDisplayName" width="145" align="center">
					<template #default="scope">
						<div class="compact-cell" style="width: 100%; box-sizing: border-box">
							<div class="date-row start-date" style="position: relative; overflow: visible">
								<span class="date-label">开工</span>
								<div style="display: flex; align-items: center; gap: 4px; flex: 1; justify-content: flex-end; overflow: visible">
									<!-- 纵向模式开工延期指示器 -->
									<el-popover v-if="Number(getCategory(scope.row, category.className)?.startDelayDays) >= 7" placement="top" :width="250" trigger="click">
										<template #reference>
											<div
												style="
													background: #ff4d4f;
													color: white;
													border-radius: 50%;
													width: 18px;
													height: 18px;
													font-size: 10px;
													font-weight: bold;
													display: flex;
													align-items: center;
													justify-content: center;
													border: 1px solid white;
													box-shadow: 0 1px 4px rgba(255, 77, 79, 0.4);
													cursor: pointer;
													flex-shrink: 0;
												"
											>
												{{ getCategory(scope.row, category.className)?.startDelayDays }}
											</div>
										</template>
										<div>
											<div style="margin-bottom: 10px; font-weight: bold">开工延期信息</div>
											<div style="font-size: 12px; color: #606266">延期天数: {{ getCategory(scope.row, category.className)?.startDelayDays }} 天</div>
										</div>
									</el-popover>
									<el-tooltip placement="top">
										<template #content>
											计划开工：{{ formatDate(getCategory(scope.row, category.className)?.planStart ?? null) }}
										</template>
										<span class="date-value">{{ formatDate(getCategory(scope.row, category.className)?.actualStart ?? null) }}</span>
									</el-tooltip>
								</div>
							</div>
							<div class="date-row end-date" style="position: relative; overflow: visible">
								<span class="date-label">完工</span>
								<div style="display: flex; align-items: center; gap: 4px; flex: 1; justify-content: flex-end; overflow: visible">
									<!-- 纵向模式延期指示器 -->
									<el-popover v-if="Number(getCategory(scope.row, category.className)?.endDelayDays) >= 7" placement="top" :width="250" trigger="click">
										<template #reference>
											<div
												style="
													background: #ff4d4f;
													color: white;
													border-radius: 50%;
													width: 18px;
													height: 18px;
													font-size: 10px;
													font-weight: bold;
													display: flex;
													align-items: center;
													justify-content: center;
													border: 1px solid white;
													box-shadow: 0 1px 4px rgba(255, 77, 79, 0.4);
													cursor: pointer;
													flex-shrink: 0;
												"
											>
												{{ getCategory(scope.row, category.className)?.endDelayDays }}
											</div>
										</template>
										<div>
											<div style="margin-bottom: 10px; font-weight: bold">完工延期信息</div>
											<div style="font-size: 12px; color: #606266">延期天数: {{ getCategory(scope.row, category.className)?.endDelayDays }} 天</div>
										</div>
									</el-popover>
									<el-tooltip placement="top">
										<template #content>
											计划完工：{{ formatDate(getCategory(scope.row, category.className)?.planEnd ?? null) }}
										</template>
										<span class="date-value">{{ formatDate(getCategory(scope.row, category.className)?.actualEnd ?? null) }}</span>
									</el-tooltip>
								</div>
							</div>
						</div>
					</template>
				</el-table-column>

				<!-- 最终状态列固定在右侧 -->
				<el-table-column label="最终状态" width="100" align="center" fixed="right" show-overflow-tooltip>
					<template #default="scope">
						<el-tag :type="getStatusType(scope.row.isAllFinished)" size="small">
							{{ scope.row.isAllFinished ? '已完成' : '进行中' }}
						</el-tag>
					</template>
				</el-table-column>

				<el-table-column label="操作" width="140" align="center" fixed="right" show-overflow-tooltip v-if="auth('planStatus:update') || auth('planStatus:delete')">
					<template #default="scope">
						<el-button icon="ele-Edit" size="small" text type="primary" @click="editDialogRef.openDialog(scope.row, '编辑计划状态')" v-auth="'planStatus:update'"> 编辑 </el-button>
						<el-button icon="ele-Delete" size="small" text type="primary" @click="delPlanStatus(scope.row)" v-auth="'planStatus:delete'"> 删除 </el-button>
					</template>
				</el-table-column>
			</el-table>

			<!-- 列表模式 - 折叠面板 -->
			<div v-if="state.displayMode === 'list'" v-loading="state.tableLoading" class="list-wrapper">
				<div class="list-collapse-box">
					<el-collapse accordion @change="handleListCollapseChange">
						<el-collapse-item v-for="item in state.tableData" :key="item.ch + item.fd" :name="item.ch + item.fd">
							<template #title>
								<div style="display: flex; align-items: center; gap: 16px; width: 100%; flex: 1">
									<el-checkbox
										:model-value="state.selectData.includes(item)"
										@update:model-value="
											(val: boolean) => {
												if (val) {
													if (!state.selectData.includes(item)) state.selectData.push(item);
												} else {
													state.selectData = state.selectData.filter((d: any) => d !== item);
												}
											}
										"
										@click.stop
										style="margin-right: 0"
									/>
									<span style="font-weight: 600; min-width: 120px">{{ item.ch }} - {{ item.fd }}</span>
									<el-tag :type="getStatusType(item.isAllFinished)" size="small">
										{{ item.isAllFinished ? '已完成' : '进行中' }}
									</el-tag>
									<span style="color: #909399; font-size: 12px; margin-left: auto">
										{{ item.categories.filter((c) => c.actualStart || c.actualEnd).length }}/{{ item.categories.length }} 项已启动
									</span>
								</div>
							</template>

							<div class="list-content">
								<div class="list-detail-layout">
										<div class="list-detail-table">
											<el-table :data="item.categories" size="small" border stripe table-layout="fixed" style="width: 100%">
												<el-table-column prop="classNameFkDisplayName" label="工序名称" min-width="120" show-overflow-tooltip>
													<template #default="scope">
														<span :class="{ 'no-plan-text': !hasPlan(scope.row) }">
															{{ scope.row.classNameFkDisplayName }}
														</span>
													</template>
												</el-table-column>

											<el-table-column label="开工日期" min-width="110" align="center">
												<template #default="scope">
													<el-tooltip placement="top">
														<template #content>
															计划开工：{{ formatDate(scope.row.planStart ?? null) }}
														</template>
														<span>{{ formatDate(scope.row.actualStart ?? null) }}</span>
													</el-tooltip>
												</template>
											</el-table-column>

											<el-table-column label="完工日期" min-width="110" align="center">
												<template #default="scope">
													<el-tooltip placement="top">
														<template #content>
															计划完工：{{ formatDate(scope.row.planEnd ?? null) }}
														</template>
														<span>{{ formatDate(scope.row.actualEnd ?? null) }}</span>
													</el-tooltip>
												</template>
											</el-table-column>

											<el-table-column label="开工延期" min-width="80" align="center">
												<template #default="scope">
													<el-tag v-if="Number(scope.row.startDelayDays) >= 7" type="danger" size="small" effect="dark">
														{{ scope.row.startDelayDays }}
													</el-tag>
													<span v-else style="color: #c0c4cc">-</span>
												</template>
											</el-table-column>

											<el-table-column label="完工延期" min-width="80" align="center">
												<template #default="scope">
													<el-tag v-if="Number(scope.row.endDelayDays) >= 7" type="danger" size="small" effect="dark">
														{{ scope.row.endDelayDays }}
													</el-tag>
													<span v-else style="color: #c0c4cc">-</span>
												</template>
											</el-table-column>

											<!-- 周期：放在完工延期后面，数值由后端计算提供 -->
											<el-table-column label="计划周期" min-width="100" align="center">
												<template #default="scope">
													<span>{{ scope.row.plannedCycleDays ?? '-' }}</span>
												</template>
											</el-table-column>

											<el-table-column label="实际周期" min-width="100" align="center">
												<template #default="scope">
													<span>{{ scope.row.actualCycleDays ?? '-' }}</span>
												</template>
											</el-table-column>
										</el-table>
									</div>
									<div class="list-detail-chart">
										<el-card class="delay-chart-card" shadow="hover" :body-style="{ padding: '12px 16px', height: '100%' }">
                            <div style="display: flex; justify-content: flex-end; gap: 6px; margin-bottom: 6px">
                                <el-button :type="item.chartMode === 'delay' ? 'primary' : 'default'" size="small" @click="item.chartMode = 'delay'">延期</el-button>
                                <el-button :type="item.chartMode === 'cycle' ? 'primary' : 'default'" size="small" @click="item.chartMode = 'cycle'">周期</el-button>
                            </div>
                            <scEcharts v-if="item.categories?.length" :option="getCategoryDelayOption(item)" height="100%" class="delay-chart-card__chart" />
											<div v-else class="list-detail-chart__empty">暂无工序数据</div>
										</el-card>
									</div>
								</div>

								<div class="item-actions" style="margin-top: 16px; padding-top: 16px; border-top: 1px solid #ebeef5">
									<el-button-group>
										<el-button icon="ele-Edit" size="small" type="primary" @click="editDialogRef.openDialog(item, '编辑计划状态')" v-auth="'planStatus:update'"> 编辑 </el-button>
										<el-button icon="ele-Delete" size="small" type="primary" @click="delPlanStatus(item)" v-auth="'planStatus:delete'"> 删除 </el-button>
									</el-button-group>
								</div>
							</div>
						</el-collapse-item>
					</el-collapse>
				</div>
			</div>

			<!-- 分页 -->
			<div class="table-pagination" style="margin-top: 10px; display: flex; justify-content: space-between; align-items: center">
				<!-- 切换按钮 -->
				<div style="margin-bottom: 10px; text-align: left">
					<el-button-group>
						<el-button :type="state.displayMode === 'table' ? 'primary' : 'default'" size="small" @click="state.displayMode = 'table'"> 表格模式 </el-button>
						<el-button :type="state.displayMode === 'compact' ? 'primary' : 'default'" size="small" @click="state.displayMode = 'compact'"> 纵向模式 </el-button>
						<el-button :type="state.displayMode === 'list' ? 'primary' : 'default'" size="small" @click="state.displayMode = 'list'"> 列表模式 </el-button>
					</el-button-group>
				</div>
				<el-pagination
					v-model:currentPage="state.tableParams.page"
					v-model:page-size="state.tableParams.pageSize"
					@size-change="(val: any) => handleQuery({ pageSize: val })"
					@current-change="(val: any) => handleQuery({ page: val })"
					layout="total, sizes, prev, pager, next, jumper"
					:page-sizes="[10, 20, 50, 100, 200, 500]"
					:total="state.tableParams.total"
					size="small"
					background
				/>
			</div>

			<ImportData ref="importDataRef" :import="planStatusApi.importData" :download="planStatusApi.downloadTemplate" v-auth="'planStatus:import'" @refresh="handleQuery" />
			<printDialog ref="printDialogRef" :title="'打印计划状态'" @reloadTable="handleQuery" />
			<editDialog ref="editDialogRef" @reloadTable="handleQuery" />
			<incompleteItemsDialog ref="incompleteItemsDialogRef" />
		</el-card>
	</div>
</template>

<script lang="ts" setup name="planStatus">
import { ref, reactive, onMounted, nextTick, watch } from 'vue';
import type { EChartsOption } from 'echarts';
import { auth } from '/@/utils/authFunction';
import { ElMessageBox, ElMessage } from 'element-plus';
import { downloadStreamFile } from '/@/utils/download';
import { usePlanStatusApi } from '/@/api/plans/planStatus';
import { usePlanIncompleteItemsApi, PlanIncompleteItemsApi } from '/@/api/plans/incompleteItems';
import { usePlanTypeApi } from '/@/api/plans/planType';
import { getAPI } from '/@/utils/axios-utils';
import { SysOrgApi } from '/@/api-services/api';
import type { SysOrg } from '/@/api-services/models';
import editDialog from '/@/views/plans/planStatus/component/editDialog.vue';
import printDialog from '/@/views/system/print/component/hiprint/preview.vue';
import ImportData from '/@/components/table/importData.vue';
import incompleteItemsDialog from './components/incompleteItemsDialog.vue';
import scEcharts from '/@/components/scEcharts/index.vue';

const planStatusApi = usePlanStatusApi();
const planTypeApi = usePlanTypeApi();
const incompleteItemsApi = usePlanIncompleteItemsApi();
const printDialogRef = ref();
const editDialogRef = ref();
const importDataRef = ref();
const incompleteItemsDialogRef = ref();
// 定义数据类型
interface Category {
	className: string;
	classNameFkDisplayName: string;
	planStart: string | null;
	planEnd: string | null;
	actualStart: string | null;
	actualEnd: string | null;
	startDelayDays: number;
	endDelayDays: number;
	plannedCycleDays?: number | null;
	actualCycleDays?: number | null;
}

interface TableRow {
	ch: string;
	fd: string;
	categories: Category[];
	isAllFinished: boolean;
    chartMode?: 'delay' | 'cycle';
}

const state = reactive({
	exportLoading: false,
	tableLoading: false,
	stores: {},
	showAdvanceQueryUI: false,
	dropdownData: {} as any,
	selectData: [] as any[],
	tableQueryParams: {} as any,
	tableParams: {
		page: 1,
		pageSize: 20,
		total: 0,
		field: 'createTime', // 默认的排序字段
		order: 'descending', // 排序方向
		descStr: 'descending', // 降序排序的关键字符
	},
	tableData: [] as TableRow[],
	categoryColumns: [] as Category[], // 存储分类列信息
	displayMode: 'table' as 'table' | 'compact' | 'list', // 显示模式：table-表格模式，compact-纵向模式，list-列表模式
	incompleteStatistics: null as PlanIncompleteItemsApi.IncompleteItemsStatistics | null, // 未完成项统计信息
});

// 页面加载时
onMounted(async () => {
	// 下拉：分类
	const planTypeData = await planTypeApi.page({ page: 1, pageSize: 99999999 }).then((res) => res.data.result);
	state.dropdownData.className =
		planTypeData?.items?.map((item: any) => ({
			value: item.id,
			label: item.name,
		})) ?? [];

	// 下拉：区域（取组织叶子节点，跟 PlanList 保持一致）
	const orgData = await getAPI(SysOrgApi)
		.apiSysOrgListGet(0)
		.then((res) => res.data.result);
	const extractAllOrgs = (orgs: SysOrg[]): Array<{ value: string; label: string }> => {
		const result: Array<{ value: string; label: string }> = [];
		orgs.forEach((org) => {
			if (org.children && org.children.length > 0) {
				result.push(...extractAllOrgs(org.children));
			} else {
				result.push({ value: org.id?.toString() || '', label: org.name || '' });
			}
		});
		return result;
	};
	state.dropdownData.workAreaId = extractAllOrgs(orgData || []);

	// 加载未完成项统计信息
	await loadIncompleteStatistics();
});

// 查询操作
const handleQuery = async (params: any = {}) => {
	state.tableLoading = true;
	state.tableParams = Object.assign(state.tableParams, params);

	// 构建查询参数，确保分页参数正确
	const queryParams = {
		page: state.tableParams.page,
		pageSize: state.tableParams.pageSize,
		keyword: state.tableQueryParams.keyword || '',
		ch: state.tableQueryParams.ch || '',
		fd: state.tableQueryParams.fd || '',
		workTime: state.tableQueryParams.workTime || '',
		status: state.tableQueryParams.status || 0,
		className: state.tableQueryParams.className ? Number(state.tableQueryParams.className) : undefined,
		workAreaId: state.tableQueryParams.workAreaId ? Number(state.tableQueryParams.workAreaId) : undefined,
	};

	console.log('查询参数:', queryParams);

	const result = await planStatusApi.page(queryParams).then((res) => res.data.result);
	state.tableParams.total = result?.total;
    state.tableData = (result?.items ?? []).map((row: any) => ({
        ...row,
        // 预处理分类数据，建立快速查找表
        categoriesMap: new Map(row.categories?.map((c: Category) => [c.className, c]) || []),
        chartMode: 'delay',
    }));

	// 提取分类列信息
	if (state.tableData.length > 0 && state.tableData[0].categories) {
		state.categoryColumns = state.tableData[0].categories;
	}

	console.log('查询结果:', result);
	state.tableLoading = false;

	// 查询完成后刷新统计信息
	await loadIncompleteStatistics();

	if (state.displayMode === 'list') {
		await nextTick();
		requestAnimationFrame(() => window.dispatchEvent(new Event('resize')));
	}
};

// 重置查询
const resetQuery = () => {
	state.tableQueryParams = {
		ch: '',
		fd: '',
		workTime: '',
		status: 0,
		className: undefined,
		workAreaId: undefined,
	};
	handleQuery();
};

// 列排序
const sortChange = async (column: any) => {
	state.tableParams.field = column.prop;
	state.tableParams.order = column.order;
	await handleQuery();
};

// 删除
const delPlanStatus = (row: any) => {
	ElMessageBox.confirm(`确定要删除吗?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			await planStatusApi.delete({ id: row.id });
			handleQuery();
			ElMessage.success('删除成功');
		})
		.catch(() => {});
};

// 批量删除
const batchDelPlanStatus = () => {
	ElMessageBox.confirm(`确定要删除${state.selectData.length}条记录吗?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			await planStatusApi.batchDelete(state.selectData.map((u) => ({ id: u.id }))).then((res) => {
				ElMessage.success(`成功批量删除${res.data.result}条记录`);
				handleQuery();
			});
		})
		.catch(() => {});
};

// 设置状态
const changePlanStatusStatus = async (row: any) => {
	await planStatusApi.setStatus({ id: row.id, status: row.status }).then(() => ElMessage.success('状态设置成功'));
};

// 导出数据
const exportPlanStatusCommand = async (command: string) => {
	try {
		state.exportLoading = true;
		if (command === 'select') {
			const params = Object.assign({}, state.tableQueryParams, state.tableParams, { selectKeyList: state.selectData.map((u) => u.id) });
			await planStatusApi.exportData(params).then((res) => downloadStreamFile(res));
		} else if (command === 'current') {
			const params = Object.assign({}, state.tableQueryParams, state.tableParams);
			await planStatusApi.exportData(params).then((res) => downloadStreamFile(res));
		} else if (command === 'all') {
			const params = Object.assign({}, state.tableQueryParams, state.tableParams, { page: 1, pageSize: 99999999 });
			await planStatusApi.exportData(params).then((res) => downloadStreamFile(res));
		}
	} finally {
		state.exportLoading = false;
	}
};

// 格式化日期
const formatDate = (dateStr: string | null) => {
	if (!dateStr) return '-';
	return dateStr.slice(0, 10); // 只显示日期部分
};

// 获取分类数据 - 使用预处理的Map快速查找，避免在模板中重复find()
const getCategory = (row: any, classNameId: string): Category | undefined => {
	return row.categoriesMap?.get(classNameId);
};

// 判断该工序是否已经排产（存在计划时间）
const hasPlan = (category: Category | undefined) => {
	if (!category) return false;
	return Boolean(category.planStart || category.planEnd);
};

// 获取状态类型
const getStatusType = (isAllFinished: boolean) => {
	return isAllFinished ? 'success' : 'warning';
};

// 加载未完成项统计信息
const loadIncompleteStatistics = async () => {
	try {
		// 使用当前查询的工作月份，如果没有则使用当前月份
		const workTime = state.tableQueryParams.workTime || `${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}`;

		const response = await incompleteItemsApi.getIncompleteItemsStatistics(workTime);
		state.incompleteStatistics = response.data.result;
	} catch (error) {
		console.error('加载未完成项统计失败:', error);
		ElMessage.error('加载统计信息失败');
	}
};

// 刷新统计信息
const refreshIncompleteStatistics = async () => {
	await loadIncompleteStatistics();
};

// 打开未完成项管理对话框
const openIncompleteItemsDialog = () => {
	// 传递当前查询的参数到对话框
	const presetParams = {
		workTime: state.tableQueryParams.workTime || `${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}`,
	};
	incompleteItemsDialogRef.value?.openDialog(presetParams);
};

const toDelayValue = (value: number | string | null | undefined) => {
	const num = Number(value);
	return Number.isFinite(num) ? num : 0;
};

const handleListCollapseChange = async () => {
	await nextTick();
	requestAnimationFrame(() => {
		window.dispatchEvent(new Event('resize'));
	});
};

const getCategoryDelayOption = (row: TableRow): EChartsOption => {
    const categories = row.categories || [];
    const labels = categories.map((c) => c.classNameFkDisplayName || c.className);
    const startDelay = categories.map((c) => toDelayValue(c.startDelayDays));
    const endDelay = categories.map((c) => toDelayValue(c.endDelayDays));
    const plannedCycles = categories.map((c) => toDelayValue(c.plannedCycleDays));
    const actualCycles = categories.map((c) => toDelayValue(c.actualCycleDays));

    const mode = row.chartMode || 'delay';
    const maxDelay = Math.max(...startDelay, ...endDelay, 0);
    const paddedMaxDelay = maxDelay < 5 ? 5 : Math.ceil(maxDelay / 5) * 5;
    const maxCycle = Math.max(...plannedCycles, ...actualCycles, 0);
    const paddedMaxCycle = maxCycle < 5 ? 5 : Math.ceil(maxCycle / 5) * 5;

	if (labels.length === 0) {
		return {
			title: {
				text: '暂无工序延期数据',
				left: 'center',
				top: 'middle',
				textStyle: {
					color: '#909399',
					fontSize: 14,
				},
			},
		};
	}

    return {
        title: {
            text: mode === 'delay' ? '分段开工/完工延期示意图' : '分段计划/实际周期示意图',
            left: 'center',
            top: 8,
            textStyle: {
                fontSize: 14,
                color: '#303133',
            },
        },
        grid: {
            top: 90,
            left: 40,
            right: 20,
            bottom: 70,
            containLabel: true,
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow',
            },
            valueFormatter: (value) => `${value ?? 0} 天`,
        },
        legend: {
            data: mode === 'delay' ? ['开工延期', '完工延期'] : ['计划周期', '实际周期'],
            top: 34,
        },
        xAxis: {
            type: 'category',
            data: labels,
            boundaryGap: mode === 'cycle',
            axisLabel: {
                interval: 0,
                rotate: 30,
                margin: 16,
            },
        },
        yAxis: {
            type: 'value',
            name: mode === 'delay' ? '延期天数' : '周期天数',
            min: 0,
            max: mode === 'delay' ? paddedMaxDelay : paddedMaxCycle,
            minInterval: 1,
            axisLabel: {
                formatter: (value: number) => `${value}`,
            },
            splitLine: {
                show: true,
                lineStyle: {
                    type: 'dashed',
                },
            },
        },
        series: mode === 'delay'
            ? [
                {
                    name: '开工延期',
                    type: 'line',
                    smooth: true,
                    data: startDelay,
                    symbol: 'circle',
                    symbolSize: 6,
                    itemStyle: { color: '#E6A23C' },
                    lineStyle: { width: 2 },
                    areaStyle: { opacity: 0.08 },
                    label: {
                        show: true,
                        position: 'top',
                        color: '#E6A23C',
                        fontSize: 10,
                        formatter: ({ value }) => `${value ?? 0}`,
                    },
                },
                {
                    name: '完工延期',
                    type: 'line',
                    smooth: true,
                    data: endDelay,
                    symbol: 'circle',
                    symbolSize: 6,
                    itemStyle: { color: '#F56C6C' },
                    lineStyle: { width: 2 },
                    areaStyle: { opacity: 0.08 },
                    label: {
                        show: true,
                        position: 'top',
                        color: '#F56C6C',
                        fontSize: 10,
                        formatter: ({ value }) => `${value ?? 0}`,
                    },
                },
            ]
            : [
                {
                    name: '计划周期',
                    type: 'bar',
                    data: plannedCycles,
                    barGap: '20%',
                    barCategoryGap: '30%',
                    barMaxWidth: 18,
                    itemStyle: { color: '#409EFF' },
                    emphasis: { focus: 'series' },
                    label: {
                        show: true,
                        position: 'top',
                        color: '#409EFF',
                        fontSize: 10,
                        formatter: ({ value }) => `${value ?? 0}`,
                    },
                },
                {
                    name: '实际周期',
                    type: 'bar',
                    data: actualCycles,
                    barGap: '20%',
                    barCategoryGap: '30%',
                    barMaxWidth: 18,
                    itemStyle: { color: '#67C23A' },
                    emphasis: { focus: 'series' },
                    label: {
                        show: true,
                        position: 'top',
                        color: '#67C23A',
                        fontSize: 10,
                        formatter: ({ value }) => `${value ?? 0}`,
                    },
                },
            ],
    };
};

watch(
	() => state.displayMode,
	async (mode) => {
		if (mode === 'list') {
			await nextTick();
			requestAnimationFrame(() => window.dispatchEvent(new Event('resize')));
		}
	}
);

watch(
	() => state.tableData.length,
	async () => {
		if (state.displayMode === 'list') {
			await nextTick();
			requestAnimationFrame(() => window.dispatchEvent(new Event('resize')));
		}
	}
);

handleQuery();
</script>
<style scoped>
:deep(.el-input),
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}

.no-plan-text {
	color: #c0c4cc;
}

/* 纵向模式样式 */
.compact-cell {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	min-height: 40px;
	padding: 2px;
	overflow: visible;
}

.date-row {
	display: flex;
	align-items: center;
	justify-content: space-between;
	width: 100%;
	margin: 0;
	padding: 0 4px;
	overflow: visible;
}

.start-date {
	border-left: 2px solid #67c23a;
	padding-left: 4px;
}

.end-date {
	border-left: 2px solid #e6a23c;
	padding-left: 4px;
}

.date-label {
	font-size: 11px;
	color: #909399;
	margin-right: 4px;
	white-space: nowrap;
}

.date-value {
	font-size: 12px;
	color: #303133;
	flex: 1;
	text-align: right;
}

/* 空值样式 */
.date-value:empty::before,
.date-value:contains('-') {
	color: #c0c4cc;
}
.date-value.has-value {
	display: inline-flex;
	align-items: center;
	justify-content: center;
	padding: 2px 8px;
	border-radius: 999px;
	background: linear-gradient(135deg, rgba(103, 194, 58, 0.18) 0%, rgba(103, 194, 58, 0.1) 100%);
	color: #4c8640;
	border: 1px solid rgba(103, 194, 58, 0.26);
	box-shadow: 0 2px 6px rgba(103, 194, 58, 0.12);
	transition: all 0.2s ease;
	font-weight: 600;
	min-width: 64px;
}

.date-value.has-value:hover {
	box-shadow: 0 3px 10px rgba(103, 194, 58, 0.22);
}

/* 统计卡片样式 */
.stat-card {
	text-align: center;
	padding: 20px;
	border-radius: 8px;
	background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
	border: 1px solid #e4e7ed;
	transition: all 0.3s ease;
}

.stat-card:hover {
	transform: translateY(-2px);
	box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.stat-card.danger {
	background: linear-gradient(135deg, #ffeaa7 0%, #fab1a0 100%);
	border-color: #e17055;
}

.stat-card.warning {
	background: linear-gradient(135deg, #fdcb6e 0%, #e84393 100%);
	border-color: #d63031;
}

.stat-number {
	font-size: 28px;
	font-weight: bold;
	color: #2d3436;
	margin-bottom: 5px;
}

.stat-label {
	font-size: 14px;
	color: #636e72;
	font-weight: 500;
}

/* 列表模式样式 */
.list-wrapper {
	width: 100%;
	display: flex;
	flex-direction: column;
	flex: 1 1 auto;
	min-height: 0;
}

.list-collapse-box {
	border: 1px solid #ebeef5;
	border-radius: 4px;
	background: #ffffff;
	margin-bottom: 10px;
	flex: 1 1 auto;
	min-height: 0;
	overflow-y: auto;
}

.list-content {
	padding: 16px 0;
}

.list-detail-layout {
	display: grid;
	grid-template-columns: minmax(0, 0.4fr) minmax(0, 0.6fr);
	gap: 16px;
	align-items: stretch;
}

.list-detail-table,
.list-detail-chart {
	min-width: 0;
	display: flex;
	flex-direction: column;
	flex: 1 1 auto;
	height: 100%;
}

.list-detail-table > .el-table {
	flex: 1 1 auto;
}

.list-detail-table {
	overflow: hidden;
}

.list-detail-table :deep(.el-table__inner-wrapper),
.list-detail-table :deep(.el-table__header-wrapper),
.list-detail-table :deep(.el-table__body-wrapper) {
	width: 100%;
	overflow-x: hidden;
}

.list-detail-table :deep(table) {
	width: 100% !important;
	table-layout: fixed;
}

.list-detail-table :deep(.cell) {
	display: block;
	width: 100%;
	overflow: hidden;
	text-overflow: ellipsis;
	text-align: inherit;
}

.list-detail-chart {
	align-items: stretch;
	justify-content: center;
	padding: 8px 0;
	min-height: 280px;
	width: 100%;
}

.list-detail-chart :deep(.sc-echarts-container) {
	height: 100%;
	width: 100%;
}

.delay-chart-card {
	flex: 1;
	display: flex;
	flex-direction: column;
	height: 100%;
}

.delay-chart-card :deep(.el-card__body) {
	display: flex;
	flex-direction: column;
	height: 100%;
	padding: 12px 16px;
}

.delay-chart-card__chart {
	flex: 1 1 auto;
}

.list-detail-chart__empty {
	color: #909399;
	font-size: 13px;
	display: flex;
	align-items: center;
	justify-content: center;
	height: 100%;
	border: 1px dashed #e4e7ed;
	border-radius: 4px;
}

.item-actions {
	display: flex;
	gap: 8px;
	justify-content: flex-end;
}

/* 折叠面板自定义样式 */
:deep(.el-collapse-item__header) {
	background: #ffffff;
	border-bottom: 1px solid #ebeef5;
	transition: all 0.3s ease;
	padding: 12px 16px;
}

:deep(.el-collapse-item__header:hover) {
	background: #f5f7fa;
}

:deep(.el-collapse-item__wrap) {
	background: #ffffff;
	border-bottom: 1px solid #ebeef5;
}

:deep(.el-collapse-item__content) {
	padding: 16px;
	background: #fafbfc;
}

/* 响应式设计 */
@media (max-width: 768px) {
	.category-list {
		grid-template-columns: 1fr;
	}

	.list-detail-layout {
		grid-template-columns: 1fr;
	}

	.list-header {
		flex-direction: column !important;
		gap: 12px !important;
	}
}
</style>
